package com.ilop.sthome.utils.greenDao.utils;

import android.util.Log;

import com.ilop.sthome.data.greenDao.AutomationBean;
import com.ilop.sthome.data.greenDao.AutomationBeanDao;
import com.ilop.sthome.data.greenDao.DefaultBean;
import com.ilop.sthome.utils.CoderUtils;
import com.ilop.sthome.utils.greenDao.manage.CommonDaoUtils;
import com.ilop.sthome.utils.greenDao.manage.DaoManager;

import java.util.ArrayList;
import java.util.List;

public class AutomationDaoUtil {

    private static final String TAG = AutomationDaoUtil.class.getSimpleName();

    private volatile static AutomationDaoUtil instance = null;
    private CommonDaoUtils<AutomationBean> mAutomationUtils;
    private AutomationBeanDao mAutomationDao;

    public static AutomationDaoUtil getInstance(){
        if (instance == null){
            synchronized (AutomationDaoUtil.class){
                if (instance == null){
                    instance = new AutomationDaoUtil();
                }
            }
        }
        return instance;
    }

    public static void setInstance(){
        instance = null;
    }

    private AutomationDaoUtil() {
        DaoManager mManager = DaoManager.getInstance();
        mAutomationDao= mManager.getDaoSession().getAutomationBeanDao();
        mAutomationUtils = new CommonDaoUtils(AutomationBean.class, mAutomationDao);
    }

    public CommonDaoUtils<AutomationBean> getAutomationDao(){
        return mAutomationUtils;
    }


    /**
     * 更细或插入数据
     * @param automationBean 自动化
     */
    public void insertOrReplace(AutomationBean automationBean){
        mAutomationDao.insertOrReplace(automationBean);
    }

    /**
     * 同步网关自动化(添加客户端没有的）
     * @param deviceName 网关
     * @param mid 自动化ID
     * @param code 设备上报状态码
     */
    public void addNewAuto(String deviceName, int mid, String code){
        AutomationBean mAutomation = new AutomationBean();
        mAutomation.setMid(mid);
        mAutomation.setCode(code);
        mAutomation.setDeviceName(deviceName);
        if(code.length()>=11){
            String name = CoderUtils.getStringFromAscii(code.substring(6,38));
            mAutomation.setName(name);
        }
        mAutomationUtils.insert(mAutomation);
    }

    /**
     * 同步网关自动化(更新客户端已有的）
     * @param automation 已有自动化
     * @param deviceName 网关
     * @param mid 自动化ID
     * @param code 设备上报状态码
     */
    public void synchronizationScene(AutomationBean automation, String deviceName, int mid, String code){
        automation.setMid(mid);
        automation.setCode(code);
        automation.setDeviceName(deviceName);
        if(code.length()>=11){
            String name = CoderUtils.getStringFromAscii(code.substring(6,38));
            automation.setName(name);
        }
        mAutomationUtils.update(automation);
    }

    /**
     * 查询所有自动化
     * @param sid 场景Id
     * @param deviceName 设备deviceName
     * @return
     */
    public boolean findAllAutoBySid(int sid, String deviceName){
        List<AutomationBean> mAutomation = findAllAutoWithoutDefaultAndTiming(deviceName);
        if (mAutomation.size()>0){
            for (AutomationBean mAuto:mAutomation) {
                String sceneId = mAuto.getSceneId();
                List<String> sceneList = CoderUtils.getSceneList(sceneId);
                if (sceneList.contains(String.valueOf(sid))) {
                    return true;
                }
            }
            return false;
        }else {
            return false;
        }
    }

    /**
     * 根据ID查询自动化
     * @param mid
     * @param deviceName
     * @return
     */
    public AutomationBean findAutomationByMid(int mid, String deviceName){
        return mAutomationDao.queryBuilder()
                .where(AutomationBeanDao.Properties.Mid.eq(mid),
                        AutomationBeanDao.Properties.DeviceName.eq(deviceName))
                .build()
                .unique();
    }

    /**
     * 查询所有自动化ID
     * @param deviceName 设备deviceName
     * @return
     */
    public List<Integer> findAllMid(String deviceName){
        List<AutomationBean> mList = mAutomationDao.queryBuilder()
                .where(AutomationBeanDao.Properties.DeviceName.eq(deviceName))
                .orderAsc(AutomationBeanDao.Properties.Mid)
                .build()
                .list();
        List<Integer> mMid = new ArrayList<>();
        for (AutomationBean auto: mList) {
            mMid.add(auto.getMid());
        }
        return mMid;
    }

    /**
     * 查询所有自动化CRC
     * @param deviceName 设备deviceName
     * @return
     */
    public List<String> findAllAutoCRC(String deviceName){
        List<AutomationBean> mList = mAutomationDao.queryBuilder()
                .where(AutomationBeanDao.Properties.DeviceName.eq(deviceName))
                .orderAsc(AutomationBeanDao.Properties.Mid)
                .build()
                .list();
        List<String> mCRC = new ArrayList<>();
        for (AutomationBean auto: mList) {
            mCRC.add(auto.getCrcCord());
        }
        return mCRC;
    }

    /**
     * 查询所有包含常用功能自动化
     * @param deviceName 网关
     * @return 自动化列表
     */
    public List<AutomationBean> findAllAutoWithDefault(String deviceName){
        List<AutomationBean> mList = new ArrayList<>();
        List<AutomationBean> auto =  mAutomationDao.queryBuilder()
                .where(AutomationBeanDao.Properties.DeviceName.eq(deviceName),
                        AutomationBeanDao.Properties.Code.isNotNull(),
                        AutomationBeanDao.Properties.Reserve.eq("00"))
                .orderAsc(AutomationBeanDao.Properties.Mid)
                .build()
                .list();
        List<AutomationBean> defeat =  mAutomationDao.queryBuilder()
                .where(AutomationBeanDao.Properties.DeviceName.eq(deviceName),
                        AutomationBeanDao.Properties.Code.isNotNull(),
                        AutomationBeanDao.Properties.Reserve.notEq("00"))
                .orderAsc(AutomationBeanDao.Properties.Mid)
                .build()
                .list();
        mList.addAll(auto);
        mList.addAll(defeat);
        return mList;
    }

    /**
     * 查询所有非默认自动化和定时自动化
     * @param deviceName
     * @return
     */
    public List<AutomationBean> findAllAutoWithoutDefaultAndTiming(String deviceName){
        return mAutomationDao.queryBuilder()
                .where(AutomationBeanDao.Properties.DeviceName.eq(deviceName),
                        AutomationBeanDao.Properties.Code.isNotNull(),
                        AutomationBeanDao.Properties.SceneId.notEq("7FFF"),
                        AutomationBeanDao.Properties.Reserve.eq("00"))
                .orderAsc(AutomationBeanDao.Properties.Mid)
                .build()
                .list();
    }

    /**
     * 所有自动化数量
     * @param mid 自动化ID
     * @param deviceName 设备deviceName
     * @return
     */
    private int findAutomationCount(int mid, String deviceName){
        return mAutomationUtils.queryByQueryBuilder(
                AutomationBeanDao.Properties.Mid.eq(mid),
                AutomationBeanDao.Properties.DeviceName.eq(deviceName)
        ).size();
    }

    /**
     * 查询输入类型子设备的默认自动化数量
     * @param recommendId 推荐Id
     * @param deviceName 网关
     * @return 默认自动化数量
     */
    public List<AutomationBean> findAutomationByInType(String recommendId, String deviceName, int deviceId){
        List<AutomationBean> mList =  mAutomationUtils.queryByQueryBuilder(
                AutomationBeanDao.Properties.Reserve.eq(recommendId),
                AutomationBeanDao.Properties.DeviceName.eq(deviceName));
        Log.i(TAG, "findAutomationByInType: " + mList.size());
        List<AutomationBean> automationList = new ArrayList<>();
        for (AutomationBean auto:mList) {
            int mDeviceId = Integer.parseInt(auto.getCode().substring(22, 26), 16);
            Log.i(TAG, "findAutomationByInType: " + mDeviceId + "--" + deviceId);
            if (deviceId == mDeviceId){
                automationList.add(auto);
            }
        }
        return automationList;
    }

    /**
     * 查询输出类型子设备的默认自动化数量
     * @param recommendId 推荐Id
     * @param deviceName 网关
     * @return 默认自动化数量
     */
    public List<AutomationBean> findAutomationByOutType(String recommendId, String deviceName, int deviceId){
        List<AutomationBean> mList =  mAutomationDao.queryBuilder()
                .where(AutomationBeanDao.Properties.Reserve.eq(recommendId),
                        AutomationBeanDao.Properties.DeviceName.eq(deviceName))
                .build()
                .list();
        List<AutomationBean> automationList = new ArrayList<>();
        if (mList.size()>0) {
            for (AutomationBean auto : mList) {
                if (auto.getOutputList().size()>0){
                    int mDeviceId = auto.getOutputList().get(0).getDevice_ID();
                    if (deviceId == mDeviceId) {
                        automationList.add(auto);
                    }
                }
            }
        }
        return automationList;
    }


    /**
     * 查询推荐自动化
     * @param defaultBean 常用功能
     * @return
     */
    public AutomationBean findAutomationByRecommendId(DefaultBean defaultBean){
        List<AutomationBean> mList =  mAutomationDao.queryBuilder()
                .where(AutomationBeanDao.Properties.DeviceName.eq(defaultBean.getDeviceName()),
                        AutomationBeanDao.Properties.Reserve.eq(defaultBean.getRecommendId()))
                .build()
                .list();
        if (mList.size()>0){
            String deviceType = defaultBean.getDeviceType();
            String deviceId = defaultBean.getDeviceId();
            for (AutomationBean auto : mList) {
                if (auto.getCode()!=null){
                    String type = auto.getCode().substring(18, 22);
                    String id = auto.getCode().substring(22, 26);
                    if (deviceType.equals(type) && deviceId.equalsIgnoreCase(id)){
                        return auto;
                    }
                }else {
                    return null;
                }
            }
            return null;
        }else {
            return null;
        }
    }

    /**
     * 查询对应设备的所有推荐自动化
     * @param defaultBean 常用功能
     * @return
     */
    public List<AutomationBean> findAutomationByDefault(DefaultBean defaultBean){
        List<AutomationBean> mList =  mAutomationDao.queryBuilder().where(AutomationBeanDao.Properties.DeviceName.eq(defaultBean.getDeviceName()),
                AutomationBeanDao.Properties.Reserve.eq(defaultBean.getRecommendId())).build().list();
        if (mList.size()>0){
            String deviceType = defaultBean.getDeviceType();
            String deviceId = defaultBean.getDeviceId();
            List<AutomationBean> mAutoList = new ArrayList<>();
            for (AutomationBean auto : mList) {
                if (auto.getCode()!=null){
                    String type = auto.getCode().substring(18, 22);
                    String id = auto.getCode().substring(22, 26);
                    if (deviceType.equals(type) && deviceId.equalsIgnoreCase(id)){
                        mAutoList.add(auto);
                    }
                }
            }
            return mAutoList;
        }else {
            return null;
        }
    }

    /**
     * 根据自动化ID查询常用功能的ID
     * @param mid 场景ID
     * @param deviceName 网关
     * @return 常用功能ID
     */
    public String findDefaultByMid(int mid, String deviceName){
        AutomationBean automationBean = AutomationDaoUtil.getInstance().findAutomationByMid(mid,deviceName);
        if (automationBean == null){
            return null;
        }else {
            return automationBean.getReserve();
        }
    }

    /**
     * 根据ID删除自动化
     * @param mid
     * @param deviceName
     */
    public void deleteByMid(int mid, String deviceName){
        mAutomationUtils.deleteByQuery(AutomationBeanDao.Properties.Mid.eq(mid),
                AutomationBeanDao.Properties.DeviceName.eq(deviceName));
    }

    /**
     * 删除网关下的自动化
     * @param deviceName
     */
    public void deleteByDeviceName(String deviceName){
        mAutomationUtils.deleteByQuery(AutomationBeanDao.Properties.DeviceName.eq(deviceName));
    }

    /**
     * 删除无效自动化
     * @param position 无效位开始如 mid大于8后面的所有自动化
     */
    public void deleteByInvalid(int position){
        mAutomationUtils.deleteByQuery(AutomationBeanDao.Properties.Mid.gt(position));
    }

    /**
     * 删除包含该子设备相关的自动化
     * @param deviceName 网关
     * @param deviceId 设备id
     */
    public void deleteBySubDevice(String deviceName, int deviceId){
        String condition = "\"deviceName\":\""+deviceName+"\",\"device_ID\":"+deviceId;
        Log.i(TAG, "deleteBySubDevice: " + condition);
        List<AutomationBean> mList = mAutomationDao.queryBuilder()
                .whereOr(AutomationBeanDao.Properties.InputList.like("%" + condition + "%"),
                        AutomationBeanDao.Properties.OutputList.like("%" + condition + "%"))
                .build()
                .list();
        mAutomationDao.deleteInTx(mList);
    }

    /**
     * 删除常用功能的自动化
     * @param defaultBean 推荐ID
     */
    public void deleteByRecommendId(DefaultBean defaultBean){
        List<AutomationBean> mList =  mAutomationDao.queryBuilder().where(AutomationBeanDao.Properties.DeviceName.eq(defaultBean.getDeviceName()),
                AutomationBeanDao.Properties.Reserve.eq(defaultBean.getRecommendId())).build().list();
        if (mList.size()>0){
            String deviceType = defaultBean.getDeviceType();
            String deviceId = defaultBean.getDeviceId();
            for (AutomationBean auto : mList) {
                if (auto.getCode()!=null){
                    String type = auto.getCode().substring(18, 22);
                    String id = auto.getCode().substring(22, 26);
                    if (deviceType.equals(type) && deviceId.equalsIgnoreCase(id)){
                        mAutomationUtils.delete(auto);
                    }
                }
            }
        }
    }
}
